package com.clouddot.baipai.ui.fragment.H;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerINewsFragmentComponent;
import com.clouddot.baipai.contract.INewsFragmentContract;
import com.clouddot.baipai.http.entity.response.getArcticByIdResponse;
import com.clouddot.baipai.http.entity.response.getArcticListResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.NewsFragmentModule;
import com.clouddot.baipai.ui.Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.adapter.H_SchoolNewsAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.SelectedBtnUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.util.viewUtil.ViewUtil.imageGetter;


/**
 * Created by wxy on 2018/8/23.
 * 横版班牌新闻的主页面
 */

public class H_NewsFrgment extends BaseFragment implements INewsFragmentContract.IView {
    private List<getArcticListResponse.ariticInfo> mDataList = new ArrayList<>();
    private H_SchoolNewsAdapter adapter;
    private TextView[] textViews = new TextView[3];
    private String currentItem = "XXXW";
    private String currentDataType = "";
    private int currentPage = 1;
    private H_ContentDailog dailog;

    private boolean isRunning = false;

    @Inject
    INewsFragmentContract.IPresenter mPresenter;
    @BindView(R.id.RecyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.school_news)
    TextView school_news;
    @BindView(R.id.notice)
    TextView notice;
    @BindView(R.id.urgency)
    TextView urgency;
    @BindView(R.id.leftLoading)
    ImageView leftLoading;
    @BindView(R.id.loadingLP)
    RelativeLayout loadingLP;
    @BindView(R.id.no)
    ImageView no;

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_news, null);
    }

    @Override
    protected void initViews() {

        DaggerINewsFragmentComponent.builder().newsFragmentModule(new NewsFragmentModule(this)).build().inject(this);
        mPresenter.getArcticList("XXXW", 1, 8);

    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        leftLoading.startAnimation(loadingAnim);
        textViews[0] = school_news;
        textViews[1] = notice;
        textViews[2] = urgency;
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        SelectedBtnUtil.selectedforText(textViews, textViews[0]);
        recyclerView.addOnScrollListener(H_UMainActivity.listener);
    }

    @OnClick({R.id.school_news, R.id.notice, R.id.urgency})
    public void onClick(View view) {
        H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;

        if (!isRunning) {
            isRunning = true;
            currentDataType = "";
            mDataList.clear();
            currentPage = 1;
            loadingLP.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            no.setVisibility(View.GONE);

            switch (view.getId()) {
                case R.id.school_news:
                    currentItem = "XXXW";
                    SelectedBtnUtil.selectedforText(textViews, textViews[0]);
                    break;
                case R.id.notice:
                    currentItem = "TZGG";
                    SelectedBtnUtil.selectedforText(textViews, textViews[1]);
                    break;
                case R.id.urgency:
                    currentItem = "JJTZ";
                    SelectedBtnUtil.selectedforText(textViews, textViews[2]);
                    break;
            }
            mPresenter.getArcticList(currentItem, currentPage, 8);
        }
    }

    @Override
    protected void loadData() {
    }

    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            school_news.performClick();
        }
    }


    /**
     *
     * @param flag 1 --> 获取新闻列表
     *             2 --> 获取新闻内容
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refulesNewsItem(object);
        } else if (flag == 2) {
            refulesNewsItemInfo(object);
        }
        loadingLP.setVisibility(View.GONE);
        isRunning = false;
    }

    @Override
    public void fail(int flag, String errMsg) {
        ToastUtil.showToast(getActivity(), errMsg);
        loadingLP.setVisibility(View.GONE);
        isRunning = false;

    }

    /**
     * 更新新闻列表数据
     * @param object
     */
    private void refulesNewsItem(Object object) {
        getArcticListResponse response = (getArcticListResponse) object;
        if (response.EntityList.isEmpty()) {
            if(mDataList.isEmpty()) no.setVisibility(View.VISIBLE);
            if (adapter != null) adapter.loadMoreEnd();
            return;
        }
        if (!currentDataType.equals(currentItem)) {
            mDataList = response.EntityList;
            adapter = new H_SchoolNewsAdapter(mDataList);
            adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getArcticList(currentItem, ++currentPage, 8);
                }
            });
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                    mPresenter.getArcticById(mDataList.get(position).Id);
                }
            });
            recyclerView.setAdapter(adapter);
            currentDataType = currentItem;
            recyclerView.setVisibility(View.VISIBLE);

        } else {
            adapter.addData(response.EntityList);
            adapter.loadMoreComplete();
        }

    }

    /**
     * 更新新闻item内容，dialog显示
     * @param object
     */
    private void refulesNewsItemInfo(Object object) {
        getArcticByIdResponse response = (getArcticByIdResponse) object;
        dailog = new H_ContentDailog(getActivity());
        dailog.getCloseView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                dailog.closeDialog();
            }
        });
        dailog.showDialog();
        dailog.getTextViews().get(0).setText(response.BaseData.Title);
        dailog.getTextViews().get(1).setText(response.BaseData.CreateTimeText);
        if (response.BaseData.Detail != null && !response.BaseData.Detail.isEmpty()) {
            final String html = EscapeUnescapeUtil.unescape(response.BaseData.Detail);
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    final Spanned sp = Html.fromHtml(html, imageGetter, null);
                    Message message = new Message();
                    message.what = MSG_ONE;
                    message.obj = sp;
                    handler.sendMessage(message);
                }
            });
        }
    }

    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    if (dailog != null) dailog.getTextViews().get(2).setText((Spanned) msg.obj);
                    break;
            }
        }
    };
}
